/*
 * @Description:定时任务
 * @Version: 2.0
 * @Autor: wiz
 * @Date: 2023-08-15 09:23:43
 * @LastEditors: zss
 * @LastEditTime: 2024-10-12 16:26:17
 */

import { Tsrv } from '@/services';

export class T_task {
  private timer: number | null = null;

  private intervalTime: number = 10000;

  private tasks: Set<Function> = new Set<Function>();

  constructor(intervalTime: number = 10000) {
    if (intervalTime !== 10000 && intervalTime > 0) {
      this.intervalTime = intervalTime;
    }
  }

  /**
   * @description: 开启任务
   * @return {*}
   * @author: wiz
   * @Date: 2023-08-15 09:53:44
   * @LastEditors: wiz
   * @LastEditTime: Do not edit
   */
  public startTask(): void {
    this.timer = window.setInterval(() => {
      Array.from(this.tasks).forEach(fn => {
        setTimeout(() => {
          // console.info(`The ${fn.name} method is being executed`);
          fn();
        }, 500);
      });
    }, this.intervalTime);
  }

  /**
   * @description: 停止任务
   * @return {*}
   * @author: wiz
   * @Date: 2023-08-15 09:53:25
   * @LastEditors: wiz
   * @LastEditTime: Do not edit
   */
  public stopTask(): void {
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
    }
  }

  /**
   * @description: 增加一个事务
   * @param {Function} p
   * @return {*}
   * @author: wiz
   * @Date: 2023-08-15 09:57:19
   * @LastEditors: wiz
   * @LastEditTime: Do not edit
   */
  public addTask(...p: Function[]): void {
    p.forEach(fn => {
      this.tasks.add(fn);
    });
  }

  /**
   * @description: 删除一个事务
   * @param {Function} p
   * @return {boolean}删除成功返回true,无返回false
   * @author: wiz
   * @Date: 2023-08-15 09:59:56
   * @LastEditors: wiz
   * @LastEditTime: Do not edit
   */
  public delTask(p: Function): boolean {
    if (this.tasks.has(p)) {
      return this.tasks.delete(p);
    }
    return false;
  }

  public switchIntervalTime(intervalTime: number): void {
    if (intervalTime > 0) {
      this.intervalTime = intervalTime;
      if (!Tsrv.noValue(this.timer)) {
        this.stopTask();
      }
      this.startTask();
    }
  }

  public getIntervalTime(): number {
    return this.intervalTime;
  }
}
